//
// Created by 11510 on 2024/6/14.
//

#include <cstring>
#include "StringBuffer.h"

/**
 * C 风格构造函数
 * @param pstr
 */
StringBuffer::StringBuffer(const char *pstr):_size(strlen(pstr)),_capacity(_size) {
    if(_size > 15){
        _buffer._pointer = new char[_size + 1]();
        strcpy(_buffer._pointer, pstr);
    }else{
        _capacity = 15;
        strcpy(_buffer._local, pstr);
    }
}
/**
 * 析构函数
 */
StringBuffer::~StringBuffer(){
    /* 短路性：短字符串直接返回，长字符串需要判空 */
    if(_capacity > 15 && _buffer._pointer){
        delete[] _buffer._pointer;
        _buffer._pointer = nullptr;
    }
}
/**
 * 重载取下标[]
 * @param idx
 * @return
 */
char& StringBuffer::operator[](size_t idx) {
    if(idx >= 0 && idx < _size){
        if(_capacity > 15){
            return _buffer._pointer[idx];
        }
        return _buffer._local[idx];
    }
    cerr << "out of range" << endl;
    static char nullchar = '\0';
    return nullchar;
}
/**
 * 重载输出流
 * @param os
 * @param rhs
 * @return
 */
ostream& operator<<(ostream & os, const StringBuffer & rhs){
    if(rhs._capacity > 15){
        os << rhs._buffer._pointer;
    }else{
        os << rhs._buffer._local;
    }
    return os;
}
